// 服务端，渲染生成环境
let express = require('express');
let ejs = require('ejs');
let path = require('path');
let fs = require('fs')

const os = require('os');
let formidable = require('formidable');

let app = express();

// 使用 req.body
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

let mysql = require('mysql');
let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'files',
    port: 3306
})
connection.connect();

app.engine('html', ejs.__express)
// 静态资源
app.use(express.static(path.join(__dirname, 'dist')))
app.use(express.static(path.join(__dirname, 'src/assets/video')))
app.use(express.static(path.join(__dirname, 'upload')))
// 静态化，渲染打包后的index文件
app.get('/', (req, res) => {
    // 默认为 views文件夹
    res.render('/index.html')
})

// 登录接口
app.get("/login", (req, res) => {
    // 请求数据在req中，res是响应给前端的
    const { username, password } = req.query;
    if (username == 'wang' && password == '123456') {
        res.json({
            code: 1,
            msg: '登录成功',
            data: null
        })
    } else {
        res.json({
            msg: '登录失败,账号密码错误',
            data: null,
            code: 0
        })
    }
})
// 测试Ajax
app.get('/getListTest', (req, res) => {
    res.send({
        msg: "获取成功",
        code: 1,
        data: ['https://img1.baidu.com/it/u=1966616150,2146512490&fm=253&fmt=auto&app=138&f=JPEG?w=751&h=500',
            "https://img0.baidu.com/it/u=468539302,3909142183&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=676",
            'https://img1.baidu.com/it/u=2204132179,643663242&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=800',
            'https://img2.baidu.com/it/u=4167581070,3859984764&fm=253&fmt=auto&app=138&f=JPEG?w=752&h=500',
            'https://img0.baidu.com/it/u=1997330805,2252719449&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
            'https://img1.baidu.com/it/u=3146001118,2834468129&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500',
            "https://img0.baidu.com/it/u=468539302,3909142183&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=676",
            "https://img1.baidu.com/it/u=3164998783,2199444470&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333",
            "https://img2.baidu.com/it/u=1033162629,653239564&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500"
        ]

    })
})
app.post('/getListTest', (req, res) => {
    // 接受数据
    req.on('data', (data) => {
    })
    res.send({
        msg: "获取成功",
        code: 1,
        data: ['https://img1.baidu.com/it/u=1966616150,2146512490&fm=253&fmt=auto&app=138&f=JPEG?w=751&h=500', 'https://img1.baidu.com/it/u=2204132179,643663242&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=800', 'https://img2.baidu.com/it/u=4167581070,3859984764&fm=253&fmt=auto&app=138&f=JPEG?w=752&h=500', 'https://img0.baidu.com/it/u=1997330805,2252719449&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500', 'https://img1.baidu.com/it/u=3146001118,2834468129&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500']
    })
})
// 获取全部
app.get("/getVideoList", (req, res) => {
    // console.log(req.header('host'))
    fs.readdir(path.resolve(__dirname, 'src/assets/video'), (err, data) => {
        if (err) {
            res.json({
                msg: '获取失败',
                data: null,
                code: 0
            })
        }
        let len = data.length;
        // 随机返回一个视频
        res.json({
            msg: '获取成功',
            data: data[randomNum(0, len - 1)],
            code: 1
        })
    })
})

app.get('/getTestLoading', (req, res) => {
    setTimeout(() => {
        res.send({
            msg: "成功",
            data: null,
            code: 1
        })
    }, 3000)
})

// 接收文件
app.post('/upload', (req, res) => {
    // let form = new formidable.IncomingForm();
    let form = new formidable.IncomingForm();
    form.uploadDir = path.join(process.cwd(), '/upload')

    let arrFile = []
    form.on('file', (...args) => {
        arrFile.push(args[1])
    })

    form.parse(req, (err, fields, files) => {
        if (err) throw err;
        let promiseList = arrFile.map((files) => {
            // 定义文件名
            return new Promise((resolve, reject) => {
                let filepath = files.filepath;
                let filename = files.originalFilename;
                let extname = path.extname(filename)
                let newFilename = files.newFilename + extname;
                // 重命名文件
                fs.rename(filepath, path.join(process.cwd() + '/upload/' + newFilename), (err) => {
                    if (err) {
                        reject()
                    }
                    resolve(newFilename)
                })
            })
        })
        Promise.all(promiseList).then((data) => {
            let result = (data || []).map((item) => {
                return new Promise((resolve, reject) => {
                    // 插入用户数据
                    connection.query(`insert into file(filepath) values('/${item}')`,
                        (err, results) => {
                            if (err) {
                                reject(err);
                            };
                            resolve({
                                filepath: "/" + item,
                                id: results.insertId
                            })
                        })
                })
            })

            Promise.all(result).then((dataBase) => {
                res.send({
                    data: dataBase,
                    message: "上传成功",
                    code: 1
                })
            }).catch((err) => {
                res.send({
                    message: '上传失败',
                    code: 0,
                    data: null
                })
            })

        }).catch(() => {
            res.send({
                message: '上传失败',
                code: 0,
                data: null
            })
        })

        // // 定义文件名
        // let filename = files.file.originalFilename;
        // // 重命名文件
        // fs.rename(files.file.filepath, path.join(process.cwd() + '/upload/' + filename), (err) => {
        //     if (err) {
        //         return res.send({
        //             message: '上传失败',
        //             flag: false,
        //         })
        //     }
        //     res.send({
        //         msg: '上传成功',
        //         data: filename,
        //         code: 1
        //     })
        // })
    })
})

// 获取
app.get('/upload/getList', (req, res) => {
    connection.query('select * from file', (err, result) => {
        res.send({
            message: '获取成功',
            data: result,
            code: 1
        })
    })
})

// 更新
app.post('/upload/update', (req, res) => {
    // 接受数据
    const id = parseInt(req.query.id);
    let form = new formidable.IncomingForm();
    form.uploadDir = path.join(process.cwd(), '/upload')

    let arrFile = []
    form.on('file', (...args) => {
        arrFile.push(args[1])
    })

    form.parse(req, (err, fields, files) => {
        if (err) throw err;
        let promiseList = arrFile.map((files) => {
            // 定义文件名
            return new Promise((resolve, reject) => {
                let filepath = files.filepath;
                let filename = files.originalFilename;
                let extname = path.extname(filename)
                let newFilename = files.newFilename + extname;
                // 重命名文件
                fs.rename(filepath, path.join(process.cwd() + '/upload/' + newFilename), (err) => {
                    if (err) {
                        reject()
                    }
                    resolve(newFilename)
                })
            })
        })
        Promise.all(promiseList).then((data) => {
            let result = (data || []).map((item) => {
                return new Promise((resolve, reject) => {
                    // 更新数据
                    connection.query(`update file set filepath="/${item}" where id="${id}"`,
                        (err, results) => {
                            if (err) {
                                reject(err);
                                return
                            };
                            resolve({
                                filepath: "/" + item,
                                id: id
                            })
                        })
                })
            })

            Promise.all(result).then((dataBase) => {
                res.send({
                    data: dataBase,
                    message: "更新成功",
                    code: 1
                })
            }).catch((err) => {
                res.send({
                    message: '更新失败',
                    code: 0,
                    data: null
                })
            })

        }).catch(() => {
            res.send({
                message: '更新失败',
                code: 0,
                data: null
            })
        })



    })
})

// 删除图片
app.delete("/upload/delete", (req, res) => {
    const id = parseInt(req.query.id);
    connection.query(`delete from file where id="${id}"`, (err, result) => {
        if (err) throw err
        res.send({
            data: { id: id },
            code: 1,
            message: "删除成功"
        })
    })
})

app.listen(8888, () => {
    console.log('    本机服务器地址：', 'http://localhost:8888', '或', `http://${getIpAddress()}:8888`)
}
)

// 生成随机整数数
function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 0;
            break;
    }
}
/**
 * 获取当前机器的ip地址
 */
function getIpAddress() {
    var ifaces = os.networkInterfaces()
    for (var dev in ifaces) {
        let iface = ifaces[dev]
        for (let i = 0; i < iface.length; i++) {
            let { family, address, internal } = iface[i]
            if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
                return address
            }
        }
    }
}